package com.example.limit.controller;

import com.example.limit.service.EnhancedPurchaseLimitService;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/v2/purchase")
public class EnhancedPurchaseController {
    
    private final EnhancedPurchaseLimitService limitService;
    
    public EnhancedPurchaseController(EnhancedPurchaseLimitService limitService) {
        this.limitService = limitService;
    }
    
    @PostMapping("/check")
    public EnhancedPurchaseLimitService.PurchaseCheckResult checkPurchaseLimit(
            @RequestParam Long userId,
            @RequestParam String productId,
            @RequestParam String categoryId,
            @RequestParam int quantity,
            @RequestParam(required = false) Boolean isNewUser,
            @RequestParam(required = false) String userLevel) {
        
        Map<String, Object> context = new HashMap<>();
        if (isNewUser != null) context.put("isNewUser", isNewUser);
        if (userLevel != null) context.put("userLevel", userLevel);
        
        return limitService.checkPurchaseLimit(userId, productId, categoryId, quantity, context);
    }
    
    @PostMapping
    public Map<String, Object> purchase(
            @RequestParam Long userId,
            @RequestParam String productId,
            @RequestParam String categoryId,
            @RequestParam int quantity,
            @RequestParam Long orderId,
            @RequestParam(required = false) Boolean isNewUser,
            @RequestParam(required = false) String userLevel) {
        
        Map<String, Object> context = new HashMap<>();
        if (isNewUser != null) context.put("isNewUser", isNewUser);
        if (userLevel != null) context.put("userLevel", userLevel);
        
        EnhancedPurchaseLimitService.PurchaseCheckResult result = 
            limitService.checkPurchaseLimit(userId, productId, categoryId, quantity, context);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", result.isPassed());
        response.put("message", result.getMessage());
        response.put("details", result.getGroupResults());
        
        if (result.isPassed()) {
            // 这里应该调用订单服务创建订单，简化处理
            response.put("orderId", orderId);
            response.put("purchaseTime", java.time.LocalDateTime.now());
        }
        
        return response;
    }
}